﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using Web.My.Models;
using System.Web.Mvc;
using Web.Core.Security;
using Web.Core.Extensions;
using Web.Core.Components;
using Ayatta.Contract.Domain;

namespace Web.My.Controllers
{
    public class OrderController : BaseController
    {
        public OrderController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="size">分页大小</param>
        /// <param name="id">订单号</param>
        /// <param name="nick">商家昵称</param>
        /// <param name="title">商品标题</param>
        /// <param name="category">订单类型</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="commentStatus">评论状态</param>
        /// <param name="beginDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <returns></returns>
        public ActionResult Index(int page = 1, int size = 20, string id = null, string nick = null, string title = null,
            OrderCategory category = OrderCategory.Normal, OrderStatus? orderStatus = null, byte? commentStatus = null, DateTime? beginDate = null, DateTime? endDate = null)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Index();
            model.Id = id;
            model.Nick = nick;
            model.Title = title;
            model.Category = category;
            model.Status = orderStatus;
            model.CommentStatus = commentStatus;
            model.BeginDate = beginDate;
            model.EndDate = endDate;
            var orders = Trade.Value.GetPagedOrders(page, size, id, identity.Id, nick, false, title, category, orderStatus, commentStatus, beginDate, endDate).ToPagedList(page, size);
            if (orders.Count > 0 && category != OrderCategory.IntegralExchange)
            {
                var orderIds = orders.Select(o => o.Id).ToArray();
                var orderItems = Trade.Value.GetOrderItems(orderIds);
                foreach (var order in orders)
                {
                    order.OrderItems = orderItems.Where(o => o.OrderId == order.Id).ToList();
                }
            }
            model.Orders = orders;
            return View(model);
        }

        //public ActionResult Auction(int page = 1, int size = 20)
        //{
        //    var identity = User.Identity.Identity();
        //    var model = new OrderControllerModel.Auction();
        //    model.Orders = AuctionService.GetPagedAuctionOrder(page, size, identity.Id).ToPagedList(page, size);
        //    return View(model);
        //}

        /// <summary>
        /// 订单详细信息
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Detail(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Detail();
            var order = Trade.Value.GetOrder(param, identity.Id, true);
            model.Order = order;
            if (order.Status == OrderStatus.SellerSendPart || order.Status == OrderStatus.WaitBuyerConfirm || order.Status == OrderStatus.Finished)
            {
                model.Shippings = Trade.Value.OrderShipmentGet(param);
            }
            return View(model);
        }

        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Memo(string param)
        {
            var identity = User.Identity.Identity();
            var model = Trade.Value.GetOrderMemo(param, identity.Id, false);
            return PartialView(model);
        }

        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="flag">Flag</param>
        /// <param name="memo">备忘</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Memo(string param, byte? flag, string memo)
        {
            var result = new MagicKit();
            if (memo.Length > 100)
            {
                result.Message = "备忘不能超过100个字！";
                return Json(result);
            }
            if (Request.IsAuthenticated)
            {
                var identity = User.Identity.Identity();
                var status = Trade.Value.UpdateOrderMemo(param, identity.Id, false, flag, memo);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "备忘失败！";
                }
            }
            else
            {
                result.Message = "请登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Cancel(string param)
        {
            var identity = User.Identity.Identity();
            var model = new MagicKit<Order>();
            if (Request.IsAuthenticated)
            {
                var order = Trade.Value.OrderStatusGet(param, identity.Id, false);
                if (order == null)
                {
                    model.Message = "订单不存在！";
                }
                else
                {
                    if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
                    {
                        model.Status = true;
                        model.Data = order;
                    }
                    else
                    {
                        model.Message = "该订单当前状态不可关闭交易！";
                    }
                }
            }
            else
            {
                model.Message = "登录超时请重新登录！";
            }
            return PartialView(model);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="reason">取消原因</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Cancel(string param, string reason)
        {
            var result = new MagicKit<Order>();
            var identity = User.Identity.Identity();
            var order = Trade.Value.OrderStatusGet(param, identity.Id, false);
            if (order == null)
            {
                result.Message = "订单不存在！";
                return Json(result);
            }
            if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
            {
                var status = Trade.Value.OrderStatusUpdate(param, identity.Id, false, OrderStatus.Canceled, reason);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "取消订单失败！";
                }
            }
            else
            {
                result.Message = "该订单当前状态不可取消！";
            }
            return Json(result);
        }

        /// <summary>
        /// 修改补充留言
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Message(string param)
        {
            var identity = User.Identity.Identity();
            var model = Trade.Value.GetOrderMemo(param, identity.Id, false);
            return PartialView(model);
        }

        /// <summary>
        /// 修改补充留言
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="message">留言信息</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Message(string param, string message)
        {
            var result = new MagicKit<string>();
            if (message.Length > 200)
            {
                result.Message = "留言信息不能超过200个字！";
                return Json(result);
            }
            if (Request.IsAuthenticated)
            {
                var identity = User.Identity.Identity();
                var status = Trade.Value.UpdateOrderBuyerMessage(param, identity.Id, message);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "更新留言信息失败！";
                }
            }
            else
            {
                result.Message = "超时，请重新登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 编辑订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Edit(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Detail();
            model.Order = Trade.Value.GetOrder(param, identity.Id, true);
            return View(model);
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="param">物流订单号</param>
        /// <returns></returns>
        public ActionResult Confirm(string param)
        {
            var result = new MagicKit<Order>();
            var identity = User.Identity.Identity();
            var shipping = Trade.Value.ShipmentGet(param);
            if (!shipping.IsOnline && shipping.Status == ShippingStatus.Created)
            {
                result.Status = Trade.Value.OrderConfirm(param, identity.Id);
            }
            return View(result);
        }


        /// <summary>
        /// 订单支付 检查订单状态等
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Pay(string param)
        {
            var url = string.Empty;
            var identity = User.Identity.Identity();

            var order = Trade.Value.OrderStatusGet(param, identity.Id, false);
            if (order != null)
            {
                if (order.Category == OrderCategory.Normal)
                {
                    if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
                    {
                        if (order.Status == OrderStatus.Pending)
                        {
                            Trade.Value.OrderStatusUpdate(order.Id, identity.Id, false, OrderStatus.WaitBuyerPay);
                        }
                        url = WebSite.Pay + "/order?param=" + param;
                    }
                    else
                    {
                        url = "/order/detail/" + param;
                    }
                }
                else if (order.Category == OrderCategory.Auction || order.Category == OrderCategory.AuctionVariant)
                {
                    if (order.Status == OrderStatus.Pending)
                    {
                        if (order.Shipment != OrderShipment.Virtual)
                        {
                            url = "/order/auction/" + param;
                        }
                    }
                    else
                    {
                        url = "/order/detail/" + param;
                    }
                }
            }
            return Redirect(url);
        }


        /// <summary>
        /// 竞购订单处理 （第一次点击支付 需完成收货地址填写）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Auction(string param)
        {
            var identity = User.Identity.Identity();

            var order = Trade.Value.GetOrder(param, identity.Id);
            if (order != null)
            {
                if (order.Shipment != OrderShipment.Virtual)
                {
                    var model = new OrderControllerModel.Auction();

                    var addresses = UserAddressList(identity.Id).Where(o => o.Category == AddressCategory.Receive).ToList();
                    var address = addresses.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                    var invoices = Passport.Value.UserInvoiceList(identity.Id);
                    var invoice = invoices.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                    model.UserAddresses = addresses;
                    model.UserAddress = address;
                    model.UserInvoices = invoices;
                    model.UserInvoice = invoice;
                    model.Order = order;

                    return View(model);
                }
                var url = order.Status != OrderStatus.Pending ? "/order/detail/" + param : WebSite.Pay + "/order/?param=" + param;

                return Redirect(url);
            }
            return Redirect("/order");
        }

        [HttpPost]
        public ActionResult Auction(string param, UserAddress userAddress, UserInvoice userInvoice)
        {
            var identity = User.Identity.Identity();
            var order = Trade.Value.GetOrder(param, identity.Id);
            if (order.Status == OrderStatus.WaitBuyerPay)
            {
                var url = WebSite.Pay + "/order/?param=" + param;
                Redirect(url);
            }
            var areas = AreaFullName(userAddress.AreaId, AreaList());
            userAddress.Province = areas.First;
            userAddress.City = areas.Second;
            userAddress.District = areas.Third;
            var status = Trade.Value.OrderAddressInvoiceSet(order.Id, identity.Id, userAddress, userInvoice);
            if (status)
            {
                var url = WebSite.Pay + "/order/?param=" + param;
                Redirect(url);
            }
            return Redirect("/order/auction/" + param);
        }

        /// <summary>
        /// 竞拍获得的拍品兑换为积分或免费拍币
        /// </summary>
        /// <param name="param">订单Id</param>
        /// <returns></returns>
        public ActionResult Exchange(string param)
        {
            var identity = User.Identity.Identity();
            var exchange = Trade.Value.GetOrderExchangeDetail(param, identity.Id);
            if (exchange != null)
            {
                var order = Trade.Value.GetOrder(param, identity.Id);
                if (order.Category == OrderCategory.AuctionVariant)
                {

                }
            }

            return PartialView();
        }

        /// <summary>
        /// 竞拍获得的拍品兑换为积分或免费拍币
        /// </summary>
        /// <param name="param">订单Id</param>
        /// <param name="exchange">兑换目标</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmExchange(string param, OrderExchange exchange)
        {
            var identity = User.Identity.Identity();
            var result = new MagicKit<string>();
            var detail = Trade.Value.GetOrderExchangeDetail(param, identity.Id);
            if (detail != null)
            {
                var time = detail.CreatedOn.ToString("yyyy-MM-dd HH:mm");
                var text = detail.Category == 0 ? "积分" : detail.Category == 1 ? "免费拍币" : string.Empty;
                result.Message = string.Format("您已于{0}选择将该订单兑换为{1}！", time, detail.Amount + text);
            }
            else
            {
                var order = Trade.Value.GetOrder(param, identity.Id);
                if (order.Category != OrderCategory.Auction || (order.Category == OrderCategory.AuctionVariant))
                {
                    result.Message = "该订单不支持兑换！";
                    return Json(result);
                }

            }

            return Json(result);
        }


    }
}
